package com.hanyizhu.demostore.controller;

import com.hanyizhu.demostore.entity.Cart;
import com.hanyizhu.demostore.service.ICartService;
import com.hanyizhu.demostore.util.JsonResult;
import com.hanyizhu.demostore.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 购物车控制层
 * @author lenovo
 */
@RestController
@RequestMapping("carts")
public class CartController extends BaseController{
    @Autowired
    private ICartService cartService;

    @RequestMapping("add_to_cart")
    public JsonResult<Void> addToCart(HttpSession session,Integer num,Integer pid){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        cartService.addToCart(uid,pid,num,username);
        return new JsonResult<>(OK);
    }

    @RequestMapping({"/",""})
    public JsonResult<List<CartVO>> getCartVo(HttpSession session){
        Integer uid = getUidFromSession(session);
        List<CartVO> data = cartService.getVoByUid(uid);
        return new JsonResult<>(OK,data);
    }

    //@PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中：URL 中的 {xxx}
    // 占位符可以通过@PathVariable(“xxx“) 绑定到操作方法的入参中。
    @RequestMapping("{cid}/num/add")
    public JsonResult<Integer> addNum(HttpSession session,@PathVariable("cid") Integer cid){
        String username = getUsernameFromSession(session);
        Integer uid = getUidFromSession(session);
        Integer data = cartService.addNum(cid, uid, username);
        return new JsonResult<>(OK,data);
    }
    @RequestMapping("{cid}/num/reduce")
    public JsonResult<Integer> reduceNum(HttpSession session,@PathVariable Integer cid){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        Integer data = cartService.reduceNum(cid, uid, username);
        return new JsonResult<>(OK,data);
    }

    //public LogUtils getMessage(
    //　　@RequestParam(value="username",defaultValue="0",required=false)String username,
    //　　Integer pageCurrent) {}
    //这里的value为前端传递的参数名称，required=false为前端也可以不传此参数
    //defaultValue="0" 若是没有传这个参数，这个参数默认为0
    @RequestMapping("list")
    public JsonResult<List<CartVO>> getVoByCid(HttpSession session,@RequestParam(value = "cids") Integer ... cid){
        Integer uid = getUidFromSession(session);
        List<CartVO> data = cartService.getVoByCid(uid, cid);
        return new JsonResult<>(OK,data);
    }
}
